/**
 * Mongo配置
 */
'use strict';

import * as Mongoose from "mongoose";
import  {fsfiles}  from  "./fsFiles";
import  {Gridfs}  from  "./gridfs";

//mongo入参
export interface DbConfig {
    host: string,
    user?: string,
    pwd?: string
}
//连接mongo
export function init(config: DbConfig) {
    // mongo 设置 promise
    (<any>Mongoose).Promise = global.Promise
    const connection = Mongoose.connect(config.host, {
        // server: {
         
        //     socketOptions: { }
        // }
        reconnectTries: Number.MAX_VALUE,
        keepAlive: 2,
        useNewUrlParser: true,
        poolSize :2
    });

    let mongoDb: any = Mongoose.connection;
    mongoDb.on('error', () => {
        console.log(`不能连接到数据库：mongodb://%s/%s:%s`, mongoDb.host, mongoDb.name, mongoDb.port);
    });
    mongoDb.once('open', () => {
        console.log(`连接到数据库：mongodb://%s/%s:%s`, mongoDb.host, mongoDb.name, mongoDb.port);
        fsfiles.makesureGrid();
        Gridfs.makesureGrid();
    });
    mongoDb.once('close', () => {
        console.log(`数据库断开连接：mongodb://%s/%s:%s`, mongoDb.host, mongoDb.name, mongoDb.port);
    });

    return connection;
}